package org.NooLab.structures;

import java.util.Observable;
import java.util.Observer;

import org.NooLab.itexx.comm.intf.CommboxIntf;
import org.NooLab.itexx.comm.tcp.box.TcpBox;
import org.NooLab.utilities.logging.PrintLog;





public class AppCommBox implements Observer, CommboxIntf{
	
	
	public TcpBox tcpBox;
	
	String name;
	
	PrintLog out = new PrintLog(2,true);

	int outPort;
	private int inPort;

	
	// ----------------------------------------------------
	public AppCommBox( String appname, int inPort, int outPort ) throws Exception{
	
		this.name = appname;
		
		tcpBox = new TcpBox( (CommboxIntf)this);
		
		this.setInPort(inPort) ;
		this.outPort = outPort;
		
		try{
			tcpBox.createReceiver( inPort, outPort, this, "") ;
			
			if (tcpBox.getTcpReceiver()!=null){
				tcpBox.createSender(outPort, inPort, "") ;
				tcpBox.addObserver(this);
			}else{
				
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if (tcpBox.getTcpReceiver()==null){
			throw(new Exception("Communication server for <"+appname+"> listening at port <"+inPort+"> failed to start"));
		} 
		
	}
	// ----------------------------------------------------

	public void close() {
		// 
		tcpBox.deleteObservers();
		
		tcpBox.getTcpReceiver().setSilentShutDown(1);
		tcpBox.getTcpReceiver().closePort();	
	}

	
	@Override
	public void deleteParentObservers(){
		
	}
	@Override
	public void addParentObserver( Observer obs){
		
	}
	
	@Override
	public void update(Observable senderObj, Object msgObj) {
		 
		out.print(2, "[<<<<<] CoWorker-AppInstance received a Tcp message...\n"+msgObj.toString());

		// decode message in dedicated routine
		// set waitforReleaseConfirmed
		
		// releaseMsg = "<action start=\"1\" mode=\"release\" >\n<process name=\"\" secret=\""+instanceGuid+"\">";
		
		// if (inPort == CoWorkerIntf._mainServerPort)
		{

			// decode message in dedicated routine
			new AppClientMsgDigest( msgObj) ;
		}
	}

	public void setInPort(int inPort) {
		this.inPort = inPort;
	}

	public int getInPort() {
		return inPort;
	}

	public String getName() {
		// 
		return name;
	}
	
	
	
}
 
